package com.ruoyi.celoan.handanUtils;

import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.SM2;
import cn.hutool.crypto.symmetric.SM4;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.celoan.handanUtils.request.HanDanDataRequest;
import com.ruoyi.celoan.handanUtils.request.HanDanDataSelectRequest;
import com.ruoyi.celoan.handanUtils.request.TokenDataRequest;
import com.ruoyi.celoan.handanUtils.response.CountryPlatformResponse;
import com.ruoyi.common.exception.CustomException;
import com.xmsme.national.secrets.*;
import com.xmsme.national.secrets.util.encoders.Base64;
import com.xmsme.national.secrets.util.encoders.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;


public class HanDanBeanNew {
    private static final Logger log = LoggerFactory.getLogger(HanDanBeanNew.class);
    public static final String myPublicKey = "049ecc3b71e8e43ae240298f9f55de4b9ad3733236ad5a3782448fe8a7d0a22f8b116c98dd9904871037d20b131b1b4d8165ef534f25205d628c5474448b5fc15e";
    public static final String myPrivateKey = "00969996be634b00d61a465f27403d0e7346d9d930d008d0f19f840604e89592dc";
    public static String appId = "872193645812376554";
    public static String appKey = "AK_6kJ8hG0fD2bA4zY6xW8vU0tS2rQ4";
    public static String appSecret = "kL1mNpQ3rS5tU7vX";


    private static final String USER_ID = "xmsme";

    public static String dealResult(SM2 sm2, CountryPlatformResponse response) {
        String decryptSm4Key = SM2Utils.decrypt(myPrivateKey, response.getKey());
        SM4Utils sm4Utils = new SM4Utils(decryptSm4Key);
        try {
            String decryptData = sm4Utils.decryptData_CBC(response.getData());
            log.info(decryptData);


//        String key2 = response.getKey();
//        log.info(key2);
//        byte[] encryptedKey = Hex.decode(key2);
//        byte[] key1 = sm2.decrypt(encryptedKey, KeyType.PrivateKey);
////        byte[] key1 = sm2.decryptFromBcd(key2, KeyType.PrivateKey);
//        SM4 sM4 = SmUtil.sm4(key1);
//        String data1 = sM4.decryptStr(response.getData());
            String digest1 = SmUtil.sm3(decryptData);
            SM2 sm2Response = new SM2(null, myPublicKey);
            boolean flag = sm2Response.verify(digest1.getBytes(), HexUtil.decodeHex(response.getSignatureData()));
//        log.info("解密信息:" + data1);
            return decryptData;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public static HanDanDataRequest jiaMiPort(String requestData, String token) {
        log.info("明文数据:{}", requestData);
        SM2KeyPair sm2KeyPair = new SM2KeyPair();
        sm2KeyPair.setPrivateKey(myPrivateKey);
        sm2KeyPair.setPublicKey(myPublicKey);

        String randomSm4Key = RandomStringUtils.getRandomString();
        HanDanDataRequest request = new HanDanDataRequest();
//        String digest = SmUtil.sm3(requestData);
//        SM2 sm2 = new SM2(myPrivateKey, myPublicKey);
//        byte[] sign = sm2.sign(digest.getBytes(), null);
//        String signatureData = HexUtil.encodeHexStr(sign);
//        String key1 = RandomUtil.randomString(16);
//        SM4 sM4 = SmUtil.sm4(key1.getBytes());
//        String data2 = sM4.encryptHex(requestData);
//        SM2 sm2Req = new SM2(null, HanDanHttpUtilsNew.publicKey());
//        String key2 = sm2Req.encryptBcd(key1, KeyType.PublicKey);
//        log.info("key1:" + key1);
//        log.info("公钥加密key2：" + key2);

        try {
            log.info("随机sm4密码:{}", randomSm4Key);
            SM4Utils sm4 = new SM4Utils(randomSm4Key);
            String encryptData = sm4.encryptData_CBC(requestData);
            log.info("请求中data:{}", encryptData);
            String summary = summary(requestData);
            String key =
                    SM2Utils.encrypt(
                            NationalSecretsUtils.hexToByte(HanDanHttpUtilsNew.publicKey()),
                            randomSm4Key.getBytes(StandardCharsets.UTF_8));

            String signatureData = sign(summary, myPrivateKey);
            request.setKey(key);
            request.setSignatureData(signatureData);
            request.setRequestData(encryptData);
            request.setPublicKey(sm2KeyPair.getPublicKey());
            request.setToken(token);
            log.info("数据加密后结果:" + JSONObject.toJSONString(request));
            return request;
        } catch (Exception e) {
            throw new CustomException(e.getMessage());
        }
    }

    public static HanDanDataSelectRequest jiaMiChaXunPort(String requestData, String token) {
        SM2KeyPair sm2KeyPair = new SM2KeyPair();
        sm2KeyPair.setPrivateKey(myPrivateKey);
        sm2KeyPair.setPublicKey(myPublicKey);
        HanDanDataSelectRequest request = new HanDanDataSelectRequest();
        String digest = SmUtil.sm3(requestData);
        SM2 sm2 = new SM2(myPrivateKey, myPublicKey);
        byte[] sign = sm2.sign(digest.getBytes(), null);
        String signatureData = HexUtil.encodeHexStr(sign);
        String key1 = RandomUtil.randomString(16);
        request.setRequestData(requestData);
        request.setPublicKey(myPublicKey);
        request.setToken(token);
        log.info("数据加密后结果:" + JSONObject.toJSONString(request));
        return request;
    }

    private static String sign(String summaryString, String privateKey) throws IllegalArgumentException, IOException {
        String privateKeys = new String(Base64.encode(NationalSecretsUtils.hexToByte(privateKey)));
        byte[] sign =
                SM2Utils.sign(
                        USER_ID.getBytes(StandardCharsets.UTF_8),
                        Base64.decode(privateKeys.getBytes(StandardCharsets.UTF_8)),
                        NationalSecretsUtils.hexToByte(summaryString));
        return NationalSecretsUtils.getHexString(sign);
    }

    public static BasePlatformRequest jiaMiToken() {
        SM2KeyPair sm2KeyPair = new SM2KeyPair();
        sm2KeyPair.setPrivateKey(myPrivateKey);
        sm2KeyPair.setPublicKey(myPublicKey);
        BasePlatformRequest request = new BasePlatformRequest();
        TokenDataRequest tokenDataRequest = new TokenDataRequest();
        tokenDataRequest.setAppId(appId);
        tokenDataRequest.setAppKey(appKey);
        tokenDataRequest.setAppSecret(appSecret);
        String data1 = JSONObject.toJSONString(tokenDataRequest);
        String summary = summary(data1);
        try {
            String signatureData = sign(summary, myPrivateKey);

            log.info("获取token参数:" + data1);
//            String digest = SmUtil.sm3(data1);
//            assert digest != null;
//            SM2 sm2 = new SM2(sm2KeyPair.getPrivateKey(), sm2KeyPair.getPublicKey());
//            byte[] sign = sm2.sign(digest.getBytes(), null);
//            String signatureData = HexUtil.encodeHexStr(sign);
            String randomSm4Key = RandomStringUtils.getRandomString();
            log.info("随机sm4密码:{}", randomSm4Key);
            SM4Utils sm4 = new SM4Utils(randomSm4Key);
            String encryptData = sm4.encryptData_CBC(data1);
            log.info("请求中data:{}", encryptData);


//            String key1 = RandomUtil.randomString(16);
//            SM4 sM4 = SmUtil.sm4(key1.getBytes());
//            String data2 = sM4.encryptHex(data1);
//            SM2 sm2Req = new SM2(null, HanDanHttpUtilsNew.publicKey());
//            String key2 = sm2Req.encryptBcd(key1, KeyType.PublicKey);
//            log.info("key1:" + key1);
//            log.info("公钥加密key2：" + key2);
            String key =
                    SM2Utils.encrypt(
                            NationalSecretsUtils.hexToByte(HanDanHttpUtilsNew.publicKey()),
                            randomSm4Key.getBytes(StandardCharsets.UTF_8));

            request.setKey(key);
            request.setSignatureData(signatureData);
            request.setRequestData(encryptData);
            request.setPublicKey(sm2KeyPair.getPublicKey());
            request.setCityName("邯郸市");
            log.info("数据加密后结果:" + JSONObject.toJSONString(request));
            return request;
        } catch (Exception e) {
            throw new CustomException(e.getMessage());
        }

    }

    private static String summary(String msg) {
        byte[] md = new byte[32];
        SM3Digest sm = new SM3Digest();
        sm.update(msg.getBytes(StandardCharsets.UTF_8), 0, msg.getBytes(StandardCharsets.UTF_8).length);
        sm.doFinal(md, 0);
        String s = new String(Hex.encode(md));
        return s.toUpperCase();
    }
}


/* Location:              D:\tuodayun\workspace\work\celoan-third-data-report-service-2.0.0-SNAPSHOT.jar!\BOOT-INF\classes\com\celoan\handanUtils\HanDanBean.class
 * Java compiler version: 8 (52.0)
 * JD-Core Version:       1.1.3
 */
